package com.liuh.test;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostMultipart {

	private static final String IMGUR_CLIENT_ID = "75b6ec6a38c6914";
												   
	  private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

	  private final OkHttpClient client = new OkHttpClient.Builder()
	  .readTimeout(25000L, TimeUnit.MILLISECONDS)
	  .writeTimeout(15000L, TimeUnit.MILLISECONDS)
	  .build();

	  public void run() throws Exception {
	    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
	    RequestBody requestBody = new MultipartBody.Builder()
	        .setType(MultipartBody.FORM)
	        .addFormDataPart("title", "Square Logo")
	        .addFormDataPart("image", "logo22.png",
	            RequestBody.create(MEDIA_TYPE_PNG, new File("d://logo.png")))
	        /*.addFormDataPart("image", "logo-square.png",
	            RequestBody.create(MEDIA_TYPE_PNG, new File("d://splash2.png")))*/
	        .build();

	    Request request = new Request.Builder()
	        .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
	        .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36")
	        .url("http://127.0.0.1:89/testC/test6")
	        .post(requestBody)
	        .build();

	    try (Response response = client.newCall(request).execute()) {
	      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

	      System.out.println(response.body().string());
	    }
	  }

	  public static void main(String... args) throws Exception {
	    new PostMultipart().run();
	  }
}
